#define N 5 //五个哲学家
#define THINKING 0 //
#define HUNGRY 1 //
#define EATING 2 //
int state[N] //定义哲学家的不同状态
Semaphore mutex=1; //互斥的信号量
Semaphore s[N]=0; //哲学家的信号量
void test(int i)
{
if((state[i]==HUNGRY)&&(state[(i-1)%5!=EATING)&&(state[(i+1)%5]!=EATING))
{
state[i]=EATING;
V(&s[i]);
}
}
state[i]=THINKING;
s[i]=0;
void philosopher(int i)
{
while(true)
{
think;
P(mutex);
state[i]=HUNGRY;
test(i);
V(mutex);
P(s[i]);
pick up the left chopstick;
pick up the right chopstick;
eat;
drop down the right chopstick;
drop down the left chopstick;
P(mutex);
state[i]=THINKING;
test((i-1)%5);
test((i+1)%5);
V(mutex);
}
}
Table of Contents
- 五个哲学家在一起吃饭,大家围坐在一个圆桌周围,每个人面前有一盘食物,一根筷子。每个哲学家有三种状态:
思考,饥饿,吃饭,怎样用计算机的角度来描述这个问题:简单的计算机语言过程
Philosopher i: do{ ... hungry ... if(F(chopstick[i])&&F(chopstick[(i+1)%5])) { P(chopstick[i]) p(chopstick[(i+1)%5]) } else break; ... eat V(chopstick[i]) V(chopstick[(i+1)%5]) ... think ... }while(1);方法需要改进
当哲学家获得其左边的筷子以后,查看其右边的筷子是否可用,如果不可用,则“谦让”,放下其已经获得的左边的筷子,等一段时间再重复这个过程。(右方优先)还有一种条件更强的解决方案,就是当且仅当左右两边的筷子都可用时,才允许他拿筷子。(左右限制)
第三种方法比较细致:规定排名奇数位的哲学家只许拿左边的筷子,排名偶数位的哲学家只需拿右边的筷子,(区别限制)
下面是第二种方案的过程:
#define N 5 //五个哲学家 #define THINKING 0 // #define HUNGRY 1 // #define EATING 2 // int state[N] //定义哲学家的不同状态 Semaphore mutex=1; //互斥的信号量 Semaphore s[N]=0; //哲学家的信号量 void test(int i) { if((state[i]==HUNGRY)&&(state[(i-1)%5!=EATING)&&(state[(i+1)%5]!=EATING)) { state[i]=EATING; V(&s[i]); } } state[i]=THINKING; s[i]=0; void philosopher(int i) { while(true) { think; P(mutex); state[i]=HUNGRY; test(i); V(mutex); P(s[i]); pick up the left chopstick; pick up the right chopstick; eat; drop down the right chopstick; drop down the left chopstick; P(mutex); state[i]=THINKING; test((i-1)%5); test((i+1)%5); V(mutex); } }下面是第三种方法的过程描述:
Void philosopher(int i) { while (true) { 思考; if i%2=0 { P(chopstick[i]); P(chopstick[(i+1)%5]); 吃饭; V(chopstick[(i+1)%5]); V(chopstick[i]); } else{ P(chopstick[(i+1)%5]); P(chopstick[i]); 吃饭; V(chopstick[i]); V(chopstick[(i+1)%5]); } } }算法的具体实现